package com.uubx.interceptor;

import com.alibaba.druid.util.StringUtils;
import com.uubx.exception.CustomerException;
import com.uubx.mapper.UserMapper;
import com.uubx.result.MessageCode;
import com.uubx.result.Result;
import com.uubx.result.ResultUtils;
import com.uubx.service.impl.UserLoginServiceImpl;
import com.uubx.utils.JedisTemplete;
import com.uubx.utils.JsonUtils;
import com.uubx.utils.ResponseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author wyy
 * @Date 2020/12/9 23:30
 * @Version 1.0
 */
public class LoginInterceptor implements HandlerInterceptor {


    @Autowired
    private HttpServletRequest request;
    @Autowired
    private JedisTemplete jedisTemplete;

    @Autowired
    private UserMapper userMapper;

    private Logger LOGGER= LoggerFactory.getLogger(LoginInterceptor.class);

    //在处理器调用之前执行 true是放行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取到token
       String token = request.getHeader("token");
        StringBuffer url = request.getRequestURL();

        LOGGER.debug("token is {}",token);
        LOGGER.debug("url is {}",url);

        //判断token是否为空
        if (StringUtils.isEmpty(token)){
            Result result = ResultUtils.buildFail(50010, "没有登录1");
            ResponseUtils.responseJson(response, JsonUtils.objectToJson(result));
            return false;
        }
        //获取redis对象
        String result = jedisTemplete.get(UserLoginServiceImpl.LOGIN + token);
        if (result==null){
            //删除数据库的token
            userMapper.deleteToken(token);
            throw new CustomerException(MessageCode.LOFIN_EMPTY);
        }
        //重新设置时间
        jedisTemplete.expire(UserLoginServiceImpl.LOGIN+token,60*60*2);






     //   2.校验token是否合法  ... TODO
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
